<template>
    <div>
        <el-breadcrumb
            separator-class="el-icon-arrow-right"
            class="breadcrumb-base"
            style="line-height: 30px;"
        >
            <el-breadcrumb-item>
                <i class="el-icon-first-aid-kit"></i>
                诊断组设置
            </el-breadcrumb-item>
        </el-breadcrumb>

        <div class="main-container">
            <el-row>
                <el-input
                    v-model="inputKey"
                    placeholder="请输入关键字"
                    class="input-form"
                    size="mini"
                >
                </el-input>
                <el-button
                    @click="searchByName"
                    type="primary"
                    size="mini"
                >搜索</el-button>
                <el-button
                    @click="subGroupDialogOpen(-1)"
                    type="primary"
                    size="mini"
                    style="float: right"
                >新增
                </el-button>
            </el-row>
            <el-row style="margin-top: 10px;">
                <base-table
                    ref="subGroupTable"
                    :data="subGroups.data"
                    :header="subGroups.header"
                    :operation="subGroups.operation"
                    :pageInfo="subGroups.pageInfo"
                    :selected="false"
                    @handleClick="subGroupTableButtonClick"
                    @pageJumpTo="subGroupTablePageJumpTo"
                    @sizeChange="subGroupTableSizeChange"
                >
                </base-table>
            </el-row>
        </div>
        <el-dialog
            :title="subGroupDialog.title"
            :visible.sync="subGroupDialog.visible"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            append-to-body
            width="25%"
        >
            <el-form
                ref="subGroupDialogForm"
                label-width="80px"
                :model="subGroupDialogForm"
                :rules="subGroupDialogFormRules"
            >
                <el-form-item
                    class="row-padding-bottom"
                    label="名称"
                    prop="name"
                >
                    <el-input
                        v-model="subGroupDialogForm.name"
                        placeholder="诊断组名称"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input
                        v-model="subGroupDialogForm.remark"
                        placeholder="请输入备注"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item label="必须初诊">
                    <el-radio-group
                        v-model="subGroupDialogForm.needFirstVisit"
                        size="mini"
                        class="radio-group"
                    >
                        <el-radio
                            v-for="t in simpleRadioList"
                            :label="t.value"
                            :key="t.value"
                            size="mini"
                        >{{ t.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="越级提交">
                    <el-radio-group
                        v-model="subGroupDialogForm.needSkipSubmit"
                        size="mini"
                        class="radio-group"
                    >
                        <el-radio
                            v-for="t in simpleRadioList"
                            :label="t.value"
                            :key="t.value"
                            size="mini"
                        >{{ t.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="必须终审">
                    <el-radio-group
                        v-model="subGroupDialogForm.needFinalVerify"
                        size="mini"
                        class="radio-group"
                    >
                        <el-radio
                            v-for="t in simpleRadioList"
                            :label="t.value"
                            :key="t.value"
                            size="mini"
                        >{{ t.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <el-row
                class="line-text"
                style="margin-top: 10px"
            >
                <el-select
                    v-model="subGroupDialog.organSelected"
                    placeholder="请选择脏器"
                    multiple
                    filterable
                    remote
                    size="mini"
                    class="picker-form"
                >
                    <el-option
                        v-for="(data, index) in subGroupDialog.organsAll"
                        :key="data.id"
                        :label="data.name"
                        :value="index"
                    >
                    </el-option>
                </el-select>
                <el-button
                    @click="organSelectedAdd"
                    style="float: right"
                    type="primary"
                    size="mini"
                >添加脏器
                </el-button>
            </el-row>
            <el-row
                class="line-text"
                style="margin-top: 10px"
            >
                <base-table
                    ref="organTable"
                    class="data-table-style"
                    :data="organTable.data"
                    :header="organTable.header"
                    :operation="organTable.operation"
                    :pageInfo="organTable.pageInfo"
                    :pageSizes="[10, 15, 20]"
                    :selected="false"
                    @handleClick="organTableButtonClick"
                >
                </base-table>
            </el-row>
            <span
                slot="footer"
                class="dialog-footer"
                style="text-align: right;"
            >
                <el-button
                    @click="subGroupDialogCommit"
                    type="primary"
                    size="mini"
                >提交</el-button>
                <el-button
                    @click="subGroupDialog.visible = false"
                    size="mini"
                >关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash';
import BaseTable from '@templates/components/BaseTable';
import { itemsPerPage } from '@/client/libs/util';
import { vxRule } from '@/client/libs/validator';

export default {
    name: 'InstitutionSubGroups',
    components: {
        BaseTable,
    },
    data() {
        return {
            inputKey: '',
            searchKey: '',

            simpleRadioList: [
                {
                    value: 0,
                    name: '否',
                },
                {
                    value: 1,
                    name: '是',
                },
            ],

            subGroups: {
                data: [],
                header: [
                    {
                        label: '诊断组名称',
                        prop: 'name',
                        width: '160',
                    },
                    {
                        label: '必须初诊',
                        prop: 'needFirstVisitName',
                        width: '107',
                    },
                    {
                        label: '越级提交',
                        prop: 'needSkipSubmitName',
                        width: '107',
                    },
                    {
                        label: '必须终审',
                        prop: 'needFinalVerifyName',
                        width: '107',
                    },
                    {
                        label: '关联脏器',
                        prop: 'organString',
                    },
                    {
                        label: '备注',
                        prop: 'remark',
                        width: '400',
                    },
                ],
                operation: [
                    {
                        label: '编辑',
                        functionKey: 'subGroupTableEdit',
                    },
                    {
                        label: '删除',
                        color: 'red',
                        functionKey: 'subGroupTableDelete',
                    },
                ],
                // 分页信息
                pageInfo: {
                    size: itemsPerPage.get(),
                    page: 1,
                    total: 0,
                },
            },
            subGroupDialog: {
                visible: false,
                title: '',
                commitMethod: '',

                organSelected: [],
                organsAll: [],
            },
            subGroupDialogForm: {
                id: 0,
                name: '',
                remark: '',
                needFirstVisit: 0,
                needSkipSubmit: 0,
                needFinalVerify: 0,
                institutionId: this.$store.state.institution.id,
            },
            subGroupDialogFormRules: {
                name: [
                    vxRule(true, null, 'blur', '请填写诊断组名称'),
                    vxRule(
                        true,
                        'length',
                        'blur',
                        '名称填写请不要超过50个字符',
                        null,
                        50
                    ),
                ],
            },

            organTable: {
                data: [],
                header: [
                    {
                        label: '脏器名称',
                        prop: 'name',
                    },
                ],
                operation: [
                    {
                        label: '删除',
                        color: 'red',
                        functionKey: 'organTableDelete',
                    },
                ],
                pageInfo: {
                    hide: true,
                    page: 1,
                    size: 0,
                    total: 0,
                },
            },
        };
    },
    mounted() {
        this.subGroupTableRequest();
    },
    computed: {},
    methods: {
        searchByName() {
            this.subGroups.pageInfo.page = 1;
            this.searchKey = this.inputKey;
            this.subGroupTableRequest();
        },
        // 表格 - 按钮点击
        subGroupTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        // 表格 - 编辑
        subGroupTableEdit(row) {
            this.subGroupDialogOpen(row.index);
        },
        // 表格 - 删除
        subGroupTableDelete(row) {
            this.$confirm('删除该诊断组, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    try {
                        // const { state } = this.$store;
                        await this.$axios({
                            // 详见 axios 请求配置项
                            method: 'DELETE',
                            url: `/PROXY-Remote/subgroups/${row.id}`,
                        }).then((res) => {
                            // 请求失败
                            if (res.data.code === 500) {
                                this.$message.warning(res.data.message);
                            }
                            if (res.data.code === 200) {
                                this.$message.success('删除成功!');
                                if (this.subGroups.data.length === 1) {
                                    if (this.subGroups.pageInfo.page > 1) {
                                        this.subGroups.pageInfo.page -= 1;
                                    }
                                }
                                this.subGroupTableRequest();
                            }
                        });
                    } catch (e) {
                        // 跳出
                    }
                })
                .catch(() => {});
        },
        // 分页跳转
        subGroupTablePageJumpTo(val) {
            this.subGroups.pageInfo.page = val;
            this.subGroupTableRequest();
        },
        // 每页显示数量改变
        subGroupTableSizeChange(val) {
            this.subGroups.pageInfo.size = val;
            this.subGroups.pageInfo.page = 1;
            this.subGroupTableRequest();
        },

        // 请求诊断组数据
        async subGroupTableRequest() {
            try {
                // const { state } = this.$store;
                await this.$axios({
                    // 详见 axios 请求配置项
                    method: 'GET',
                    url: '/PROXY-Remote/subgroups',
                    params: {
                        size: this.subGroups.pageInfo.size,
                        page: this.subGroups.pageInfo.page - 1,
                        name: this.searchKey,
                    },
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }

                    // 请求成功
                    const result = res.data;
                    // 分页信息
                    this.subGroups.pageInfo = {
                        total: result.pageInfo.total,
                        page: result.pageInfo.page + 1,
                        size: result.pageInfo.size,
                    };
                    // 查询结果数据
                    this.subGroups.data = [];
                    result.data.forEach((t, index) => {
                        const item = t;
                        item.index = index;
                        // 脏器数据处理
                        item.organList = [];
                        item.organString = '';
                        item.organs.forEach((organ) => {
                            item.organList.push({
                                id: organ.id,
                                name: organ.name,
                            });
                            item.organString += `${organ.name} `;
                        });
                        // 是否必须初诊
                        item.needFirstVisitName = t.needFirstVisit
                            ? '是'
                            : '否';
                        // 能否越级提交
                        item.needSkipSubmitName = t.needSkipSubmit
                            ? '是'
                            : '否';
                        // 是否必须终审
                        item.needFinalVerifyName = t.needFinalVerify
                            ? '是'
                            : '否';

                        this.subGroups.data.push(item);
                    });
                });
            } catch (e) {
                // 跳出
            }
        },
        // 新增/编辑 对话框
        subGroupDialogOpen(index) {
            this.subGroupDialogForm = {
                id: 0,
                name: '',
                remark: '',
                needFirstVisit: 0,
                needSkipSubmit: 0,
                needFinalVerify: 0,
                institutionId: this.$store.state.institution.id,
            };

            this.subGroupDialog.organSelected = [];

            if (index < 0) {
                this.subGroupDialog.title = '新增诊断组';
                this.subGroupDialog.commitMethod = 'POST';
                delete this.subGroupDialogForm.id;

                this.organTable.data = [];
            } else {
                this.subGroupDialog.title = '编辑诊断组';
                this.subGroupDialog.commitMethod = 'PUT';

                // 赋值
                console.log('this.subGroupDialogForm', this.subGroupDialogForm);
                Object.keys(this.subGroupDialogForm).forEach((key) => {
                    this.subGroupDialogForm[key] =
                        this.subGroups.data[index][key];
                });
                this.organTable.data = _.clone(
                    this.subGroups.data[index].organList
                );
            }

            this.organsRequestAll();
            this.subGroupDialog.visible = true;
        },
        subGroupDialogCommit() {
            this.$refs.subGroupDialogForm.validate(async (valid) => {
                if (valid) {
                    // 脏器数据结构格式化
                    this.subGroupDialogForm.organs = [];
                    this.organTable.data.forEach((t) => {
                        this.subGroupDialogForm.organs.push({
                            id: t.id,
                        });
                    });
                    try {
                        // const { state } = this.$store;
                        await this.$axios({
                            // 详见 axios 请求配置项
                            method: this.subGroupDialog.commitMethod,
                            url: '/PROXY-Remote/subgroups',
                            data: this.subGroupDialogForm,
                        }).then((res) => {
                            // 请求失败
                            if (res.data.code !== 200) {
                                throw new Error(res.data);
                            }

                            // 请求成功
                            this.$message.success(
                                `${this.subGroupDialog.title}成功`
                            );

                            this.subGroupDialog.visible = false;
                            this.subGroupTableRequest();
                        });
                    } catch (e) {
                        // 跳出
                    }
                }
            });
        },
        organSelectedAdd() {
            let isAddOne = false;
            if (this.subGroupDialog.organSelected.length === 0) {
                this.$message.warning('请选择脏器');
                return;
            }
            this.subGroupDialog.organSelected.forEach((index) => {
                const organ = this.subGroupDialog.organsAll[index];
                const isRepeat = this.organTable.data.some(
                    (t) => t.name === organ.name
                );
                if (!isRepeat) {
                    this.organTable.data.push(organ);
                    isAddOne = true;
                }
            });
            if (!isAddOne) {
                this.$message.warning('脏器重复');
            }
            this.subGroupDialog.organSelected = [];
        },
        // 对话框 - 脏器表格
        organTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        organTableDelete(row) {
            this.organTable.data.forEach((t, index) => {
                if (t.name === row.name) {
                    this.organTable.data.splice(index, 1);
                }
            });
        },
        // 请求脏器数据
        async organsRequestAll() {
            try {
                const { state } = this.$store;
                await this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/organs/listAll',
                    params: {
                        institutionId: state.institution.id,
                    },
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }

                    // 请求成功
                    const result = res.data;
                    this.subGroupDialog.organsAll = [];
                    result.data.forEach((t) => {
                        this.subGroupDialog.organsAll.push({
                            id: t.id,
                            name: t.name,
                        });
                    });
                });
            } catch (e) {
                // 跳出
            }
        },
    },
};
</script>

<style scoped>
.row-padding-bottom {
    padding-bottom: 10px;
}
.data-table-style >>> .el-table__fixed-body-wrapper {
    top: 40px !important;
}
</style>
